package cn.wh.db.router.strategy;

import cn.wh.db.router.DBContextHolder;
import cn.wh.db.router.DBRoutingConfig;
import cn.wh.db.router.bean.RoutingEntity;

/**
 * @Author wh
 * @Description 创建模板 实现重复方法 控制流程
 * @Date 2023/3/29 8:29
 * @Version 1.0
 **/
public abstract class DBRoutingBase implements IDBRoutingStrategy {

    //属性配置类
    protected final DBRoutingConfig dbRoutingConfig;

    protected DBRoutingBase(DBRoutingConfig dbRoutingConfig) {
        this.dbRoutingConfig = dbRoutingConfig;
    }


    @Override
    public void doRouter(String dbKey) {
        RoutingEntity routingEntity = this.doRouting(dbKey);
        //设置上下文对象
        this.setDBKey(routingEntity.getDbIdx());
        this.setTBKey(routingEntity.getTbIdx());
    }

    //计算路由 并返回 库表索引实体对象
    protected abstract RoutingEntity doRouting(String dbKey);




    @Override
    public DBRoutingConfig getDBRoutingConfig() {
        return dbRoutingConfig;
    }

    @Override
    public void setDBKey(String dbIdx) {
        DBContextHolder.setDBKey(dbIdx);
    }

    @Override
    public void setTBKey(String tbIdx) {
        DBContextHolder.setTBKey(tbIdx);
    }

    @Override
    public int dbCount() {
        return dbRoutingConfig.getDbCount();
    }

    @Override
    public int tbCount() {
        return dbRoutingConfig.getTbCount();
    }

    @Override
    public void clear() {
        DBContextHolder.clearDBKey();
        DBContextHolder.clearTBKey();
    }
}
